package com.translate.web.service.impl;

import com.translate.web.constant.RedisConstant;
import com.translate.web.dao.RoleMenuRelationMapper;
import com.translate.entity.RoleMenuRelation;
import com.translate.web.service.IRoleMenuRelationService;
import com.basic.service.impl.BaseServiceImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class RoleMenuRelationServiceImpl extends BaseServiceImpl<RoleMenuRelation> implements IRoleMenuRelationService {
	
	private RedisTemplate<String, List<RoleMenuRelation>> redisTemplate;

	
	@Autowired
	public void setRedisTemplate(RedisTemplate<String, List<RoleMenuRelation>> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	public RoleMenuRelationServiceImpl(RoleMenuRelationMapper mapper) {
		super(mapper);
	}

	protected Class<RoleMenuRelation> getEntityClass() {
		return RoleMenuRelation.class;
	}

	@Override
	public <VO> List<RoleMenuRelation> getRoleMenuRelationToCache(List<VO> vos, Function<VO, Integer> function) {
	
		Integer[] ids = vos.stream().map(e->function.apply(e)).toArray(Integer[]::new);
		
		return this.roleMenuRelationToCache(ids);
	}
	
	/**
	 * 角色菜单缓存
	 * @param id
	 * @return
	 */
	public List<RoleMenuRelation> roleMenuRelationToCache(Integer[] ids) {
		
		String key = RedisConstant.getRoleMenuRelationKey(ids);
		
		ValueOperations<String, List<RoleMenuRelation>> valueOperations = this.redisTemplate.opsForValue();
		
		List<RoleMenuRelation> order = valueOperations.get(key);
		
		if (null != order) {
			return order;
		}
		
		order = this.getDataByIds(ids);
		
		if (null == order) {
			order = new ArrayList<RoleMenuRelation>(0);
			
			valueOperations.set(key, order, 3, TimeUnit.SECONDS);
			
			return order;
		}
		
		valueOperations.set(key, order, 12, TimeUnit.SECONDS);

		return order;
		
	}

	@Override
	public <VO> Long[] getMenuIds(List<VO> vos, Function<VO, Integer> function) {
		
		List<RoleMenuRelation> menuRelations = this.getRoleMenuRelationToCache(vos, function);
		
		return menuRelations.stream().map(e->e.getMenuId()).toArray(Long[]::new);
		
	}
}